<?php

namespace App\Console\Commands;

use App\Http\Controllers\SendmsController;
use App\Models\Admin\SupplierSmsConfig;
use App\Models\Admin\Supplier;
use App\Models\Admin\SupplierBalanceChangeRecord;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Mockery\Exception;

class BalanceWarn extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'app:balance-warn';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '预警信息';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        DB::beginTransaction();
        try{
            $supplier_ids = Supplier:: where('account_verification','=',1) -> select('id','platform_fee_expiration_time','phone','company_name','actual_name','balance') -> get() -> toArray();
            foreach($supplier_ids as $k=>$v){
                $over_day = date('Y-m-d',$v['platform_fee_expiration_time']);
                $connect = dbRegister($v['id']);
                $time_status = DB::connection($connect) -> table('xn_supplier_status')->where('supplier_id','=',$v['id']) -> value('time_status');
                if(date('Y-m-d',time()) == $over_day){
                    DB::connection($connect) -> table('xn_supplier_status')->where('supplier_id','=',$v['id']) -> update(['status'=>2]);
                    Log::channel('task')->info($v['actual_name']."供应商的服务已到期，不能下单\r\n");
                    continue;
                }
                if($time_status == 1){
                    $endday=date('Y-m-d',strtotime('+7 day'));
                }else if($time_status == 2){
                    $endday=date('Y-m-d',strtotime('+15 day'));
                }else if($time_status == 3){
                    $endday=date('Y-m-d',strtotime('+30 day'));
                }
                if($endday == $over_day){
                    $sms_config = SupplierSmsConfig::where('sid',$v['id']) -> where('state',2) -> select('templateCode','signName') -> first();
                    $code = $this -> senemail($v['phone'],$v['actual_name'],$sms_config ->templateCode,$sms_config -> signName );
                    if(!$code){
                        Log::channel('task')->info($v['actual_name']."信息发送失败".$code."\r\n");
                        continue;
                    }
                    $this -> mysql($v,0.1);
                    Log::channel('task')->info($v['actual_name']."信息发送成功\r\n");
                }
            }
            Db::commit();
        }catch (Exception $exception){
            DB::rollBack();
            Log::channel('task')->info($exception -> getMessage());
        }
    }

    public function senemail($phone,$name,$templateCode,$signName)
    {
        $res = SendmsController::main([
            "phoneNumbers" => $phone,
            "signName" => $signName,
            "templateCode"=> $templateCode,
            "templateParam"=>"{'name':'".$name."'}"
        ]);
        if ($res['code'] == 'OK') {
            return true;
        } else {
            return false;
        }
    }

    public function mysql($info,$money){
        Supplier::where('id',$info['id']) -> decrement('balance',$money);
        $data = [
            'sid'=>$info['id'],
            'order_no'=> date('YmdHis').rand(100000000000000000,999999999999999999),
            'type'=>3,
            'money'=>$money,
            'genre'=>2,
            'before_money'=>$info['balance'],
            'after_money'=>$info['balance'] - $money,
            'capitalized_amount'=>'零点一元',
            'change_description'=>'余额时间提醒发送短信',
            'create_time'=>date('Y-m-d H:i:s')
        ];
        SupplierBalanceChangeRecord::insert($data);
    }
}
